#include <vector>
#include <string>
#include <fstream>
#include <sstream>

#include "objloader.h"

cObjLoader objLoader;

using std::string;
using std::istringstream;
using std::ifstream;

////////// cOBJLOADER... //////////

bool cObjLoader::loadObj(std::string file, cObjModel *m) {
	ifstream input(file.c_str());
	string buffer;
	
	if ( !input ) {
		return false;
	}
	
	while ( getline(input, buffer) ) {
		std::istringstream line(buffer);
		string line_t;
		
		if (buffer.substr(0,2) == "vn") {
			float f1, f2, f3;
			line >> line_t >> f1 >> f2 >> f3;
			m->normal.push_back( cObjNormal(f1, f2, f3) );
		} 
		else if (buffer.substr(0,2) == "vt") {
			float f1, f2;
			line >> line_t >> f1 >> f2;
			m->texCoord.push_back( cObjTexCoord(f1, f2) );
		} 
		else if (buffer.substr(0,1) == "v") {
			float f1, f2, f3;
			line >> line_t >> f1 >> f2 >> f3;
			m->vertex.push_back( cObjVertex(f1, f2, f3) );
		}
		else if (buffer.substr(0,1) == "f") {
			m->face.push_back( cObjFace() );
			string element;
			line >> line_t;
			
			while (line >> element) {
				string::size_type spos = 0;
				string::size_type epos;
				
				epos = element.find('/');
				if (epos == string::npos) {
					return false;
				}
				istringstream vind(element.substr(spos, epos));
				
				spos = epos+1;
				epos = element.find('/', spos);
				if (epos == string::npos) {
					return false;
				}
				istringstream vtind(element.substr(spos, epos-spos));
				istringstream vnind(element.substr(epos+1));
				
				int vi, vti, vni;
				vind >> vi; vtind >> vti; vnind >> vni;
				  
				m->face.back().vertex.push_back(vi);
				m->face.back().texCoord.push_back(vti);
				m->face.back().normal.push_back(vni);
			}
		}
	}
	
	input.close();
	
	return true;
}